<template>
  <div>
    <div class="modal_body">
      <div class="form-wrap">
        <el-card style="margin: 6px">
          <div class="menu-wrap">
            <el-input
              v-model="deptName"
              :placeholder="$t('device.device-linkage.188958-0')"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px; margin-right: 10px"
            />
            <el-tree
              :default-expanded-keys="[100]"
              :data="deptOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="id"
              highlight-current
              @node-click="handleNodeClick"
            />
          </div>
        </el-card>
        <el-card style="margin: 6px 6px 0 6px">
          <div style="height: 380px" class="deviceTable">
            <!-- <el-tabs v-model="activeName1" @tab-click="handleClick">
            <el-tab-pane
              :label="$t('device.device-linkage.188958-1')"
              name="first"
            ></el-tab-pane>
            <el-tab-pane
              :label="$t('device.device-linkage.188958-2')"
              name="second"
            ></el-tab-pane>
            <el-tab-pane
              :label="$t('device.device-linkage.188958-3')"
              name="third"
            ></el-tab-pane>
          </el-tabs> -->
            <el-input
              v-model="queryParams.serialNumber"
              :placeholder="$t('device.device-edit.148398-2')"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 10px; margin-right: 10px"
              @keydown.enter.native="getDeviceList"
            />
            <el-menu
              ref="elmenu"
              class="menu-wrap"
              style="margin-right: 10px; height: 335px"
              :default-openeds="['1']"
            >
              <el-submenu index="1" style="margin-left: -5px">
                <template slot="title">
                  <i class="el-icon-menu"></i>
                  <span style="font-size: 14px; padding: 0"
                    >{{ $t("device.device-linkage.188958-5") }}(
                    {{ deviceList.length + "/" + total }} )</span
                  >
                </template>
                <el-menu-item
                  v-for="item in deviceList"
                  :key="item.serialNumber"
                  :index="item.serialNumber"
                  class="custom-menu-item"
                  @click="handleTypeClick(item)"
                >
                  {{ item.deviceName }}
                </el-menu-item>
              </el-submenu>
            </el-menu>
            <el-pagination
              v-show="total > 0"
              :total="total"
              small
              :current-page.sync="queryParams.pageNum"
              :page-size="queryParams.pageSize"
              layout="prev, pager, next"
              @current-change="getDeviceList"
            ></el-pagination>
          </div>
        </el-card>
      </div>
      <div class="right_box">
        <div class="echarts_box">
          <div class="title">
          <div>
            <el-date-picker
              v-model="timeslot"
              type="month"
              align="right"
              size="mini"
              unlink-panels
              :placeholder="$t('placeholder.tunnellightingsystem_energyconsumptionanalysis_placeholder_selectmonth')"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </div>
          <div class="btn_box">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-arrow-left"
              @click="lastmonth"
              >{{ $t("table.lastmonth") }}</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="nextmonth"
              :disabled="nextDisabled"
              >{{ $t("table.nextmonth")
              }}<i class="el-icon-arrow-right el-icon--right"></i
            ></el-button>
          </div>
        </div>
          <Energyanalysisdata
            :energyanalysisinfo="energyanalysisinfo"
          ></Energyanalysisdata>
        </div>

        <div class="table_box">
          <el-table :data="tableData" style="width: 100%" height="460">
            <el-table-column prop="deviceName" :label="tableOneTitle">
            </el-table-column>
            <el-table-column prop="date" label="日期"> </el-table-column>
            <el-table-column prop="awpt" label="消耗电能"> </el-table-column>
            <el-table-column prop="energy" label="累计消耗电能">
            </el-table-column>
          </el-table>
          <div class="modal_bottom">
            <el-pagination
              :small="true"
              :background="true"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage"
              layout="total,sizes, prev, pager, next, jumper"
              :page-sizes="[15, 30, 60]"
              :total="total2"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { deptsTreeSelect } from "@/api/iot/device";
import { listDeviceShort } from "@/api/iot/device";
import Energyanalysisdata from "@/components/echarts/energyanalysisdata";
export default {
  components: {
    Energyanalysisdata,
  },
  data() {
    return {
      deptOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      deptName: "",
      timeslot: "",
      starttime: "",
      endtime: "",
      pickerOptions: {
        // 设置不能选择的日期
        onPick: ({ maxDate, minDate }) => {
          this.choiceDate0 = minDate.getTime();
          if (maxDate) {
            this.choiceDate0 = "";
          }
        },
        disabledDate: (time) => {
          let choiceDateTime = new Date(this.choiceDate0).getTime();
          const minTime = new Date(choiceDateTime).setMonth(
            new Date(choiceDateTime).getMonth() - 1
          );
          const maxTime = new Date(choiceDateTime).setMonth(
            new Date(choiceDateTime).getMonth() + 1
          );
          const min = minTime;
          const newDate =
            new Date(new Date().toLocaleDateString()).getTime() +
            24 * 60 * 60 * 1000 -
            1;
          const max = newDate < maxTime ? newDate : maxTime;
          //如果已经选中一个日期 则 返回 该日期前后一个月时间可选
          if (this.choiceDate0) {
            return time.getTime() < min || time.getTime() > max;
          }
          //若一个日期也没选中 则 返回 当前日期以前日期可选
          return time.getTime() > newDate;
        },
      },
      nextDisabled: true,
      energyanalysisinfo: {
        collectionTime: null,
      },
      tableData: [],
      total: 0,
      tableOneTitle: this.$t('title.tunnellightingsystem_systemmanagement_title_devicename'),
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        deptId: undefined,
        showChild: true,
        status: "",
        serialNumber: "",
      },
      deviceList: [],
      deviceInfo: null,
      checkDevice: null,
      total2:0,
    };
  },
  mounted() {
    this.getAllUserList();
    this.getCurrentDate();
    this.$nextTick(() => {
      this.getDeviceList();
    });
  },
  watch: {
    timeslot: {
      handler(val) {
        let end = val[1];
        let time2 = new Date(end).getTime();
        let now = new Date().getTime();
        if (time2 + 24 * 60 * 60 * 1000 * 31 > now) {
          this.nextDisabled = true;
        } else {
          this.nextDisabled = false;
        }
      },
    },
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    getDeviceList() {
      // if (this.queryParams.deptId == undefined) {
      //     //默认机构
      //     this.queryParams.deptId = 100;
      // }
      listDeviceShort(this.queryParams).then((response) => {
        this.deviceList = response.rows;
        this.deviceInfo = response.rows[0];
        this.checkDevice = response.rows[0].serialNumber;
        if (this.deviceId === 0) {
          this.deviceId = this.deviceList[0].deviceId;
        }
        this.total = response.total;
      });
    },
    renderContent(h, { node, data, store }) {
      if (data.label) {
        return h("span", data.label);
      } else {
        return h("span", data.groupName);
      }
    },
    getAllUserList() {
      let that = this;
      deptsTreeSelect().then((response) => {
        if (response.data.length > 0) {
          this.deptOptions = this.replaceGroupChildrenWithChildren(
            response.data
          );
          let deptId = this.$store.state.user.deviceInfo.deptId;
          if (deptId) {
            that.$nextTick(() => {
              that.$refs.tree.setCurrentKey(deptId);
            });
          }
        } else {
          this.deptOptions = {};
        }
      });
    },
    replaceGroupChildrenWithChildren(treeData) {
      return treeData.map((newNode) => {
        if (newNode.groupChildren && newNode.groupChildren.length > 0) {
          for (let i in newNode.groupChildren) {
            newNode.groupChildren[i].label = newNode.groupChildren[i].groupName;
          }
          let obj = {
            label: this.$t(
              "title.tunnellightingsystem_systemmanagement_title_groupinformation"
            ),
            id: 0,
            children: newNode.groupChildren,
          };
          if (newNode.children && newNode.children.length > 0) {
            newNode.children.unshift(obj);
          } else {
            newNode.children = [obj];
          }
        }

        // 如果节点有 children，递归处理子节点
        if (newNode.children && newNode.children.length > 0) {
          this.replaceGroupChildrenWithChildren(newNode.children);
        }

        return newNode;
      });
    },
    formatDate(date) {
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      return year + "-" + month;
    },
    getCurrentDate() {
      let now = new Date();
      let year = now.getFullYear();
      let month = now.getMonth() + 1;
      let firstDay = new Date(year, month - 1, 1);

      let start = this.formatDate(firstDay);
      let end = this.formatDate(now);
      let data = this.formatDate(firstDay);

      this.timeslot = data;
    },
    handleNodeClick(data) {
      if (data.groupId) {
        this.tableOneTitle = this.$t('title.tunnellightingsystem_systemmanagement_title_areaname')
        this.queryParams.groupId = data.groupId;
      } else {
        this.queryParams.groupId = null;
      }
      if (data.id == 0) {
        return;
      }
      this.queryParams.deptId = data.id;
      if(data.deptUserId){
        this.tableOneTitle = this.$t('table.projectname')
      }
      this.getDeviceList();
    },
    filterNode(value, data, node) {
      if (data.label) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      } else if (node.parent.label.indexOf(value) !== -1) {
        return true;
      }
    },
    lastmonth() {
      let time = this.timeslot
      let data = new Date(time);
      data.setMonth(data.getMonth() - 1);
      this.timeslot = this.formatDate(data);
    },
    nextmonth() {
      let time = this.timeslot
      let data = new Date(time);
      data.setMonth(data.getMonth() + 1);
      this.timeslot = this.formatDate(data);
    },
    handleSizeChange() {},
    handleCurrentChange() {},
    currentPage() {},
    handleTypeClick(){
      this.tableOneTitle = this.$t('title.tunnellightingsystem_systemmanagement_title_devicename')
    },
  },
};
</script>

<style scoped>
.modal_body {
  height: 815px;
  padding: 0;
  margin: 0;
  background: transparent;
  display: flex;
}
.form-wrap >>> .el-card__body {
  width: 312px;
}
.left_box {
  width: 20%;
  background: #fff;
  overflow-y: scroll;
}
.scroll ::-webkit-scrollbar {
  width: 0;
}

/* 针对Firefox隐藏滚动条 */
.left_box {
  scrollbar-width: none;
}
.right_box {
  margin-left: 3px;
  width: 77%;
  background-color: #edeef0;
  margin-top: 5px;
  padding: 10px;
  border-radius: 5px;
}
.right_box .btn_box {
  margin-left: 10px;
}
.title {
  display: flex;
}
.table_box {
  margin-top: 5px;
}
.modal_bottom {
  text-align: center;
}
.menu-wrap {
  margin-top: -5px;
  height: 345px;
  overflow-x: auto;
  overflow-y: auto;
  padding-left: 0 !important;
}
.form-wrap {
  margin-left: 8px;
}
.modal_bottom >>> .el-pagination {
  text-align: center;
  background-color: #fff;
  height: 35px;
  padding: 0;
  text-align: center;
  padding-top: 5px;
}
.echarts_box {
  background-color: #fff;
  padding: 5px;
}
.echarts_box >>> .el-date-editor.el-input, .el-date-editor.el-input__inner{
  width: 150px;
}
</style>